package com.martin.lib_base.ui.screen

import androidx.annotation.FloatRange
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.pager.PagerState
import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.TabPosition
import androidx.compose.material3.TabRow
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.lerp
import androidx.compose.ui.unit.sp
import com.martin.lib_base.ui.theme.ColorPrimary
import com.martin.lib_base.ui.theme.ColorTextGray
import com.martin.lib_base.ui.theme.ColorTextNormal
import kotlinx.coroutines.launch
import kotlin.math.abs

/**
 * @author：孟凡华
 * @date：2023/7/10
 * @desc：
 */

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun CommonTabRow(
    tabs: List<String>,
    pagerState: PagerState,
    backgroundColor: Color = Color.White,
    modifier: Modifier = Modifier
        .fillMaxWidth()
        .height(42.dp)
) {
    val scope = rememberCoroutineScope()
    TabRow(
        selectedTabIndex = pagerState.currentPage,
        containerColor = backgroundColor,
        modifier = modifier,
        divider = {},
        indicator = { tabPositions ->
            CommonTabIndicator(
                tabPositions = tabPositions,
                pagerState = pagerState
            )
        }
    ) {
        tabs.forEachIndexed { index, title ->
            val selected = index == pagerState.currentPage
            Tab(
                selected = selected,
                onClick = { scope.launch { pagerState.animateScrollToPage(index) } },
                selectedContentColor = ColorPrimary,
                unselectedContentColor = Color.LightGray,
            ) {
                Text(
                    text = title,
                    fontSize = 13.sp,
                    color = if (selected) ColorPrimary else Color(0xff828282),
                )
            }
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun CommonScrollableTabRow(
    tabs: List<String>,
    pagerState: PagerState,
    modifier: Modifier = Modifier
        .fillMaxWidth()
        .height(42.dp)
) {
    val scope = rememberCoroutineScope()
    ScrollableTabRow(
        selectedTabIndex = pagerState.currentPage,
        containerColor = Color.White,
        modifier = modifier,
        divider = {},
        edgePadding = 0.dp,
        indicator = { tabPositions ->
            CommonTabIndicator(
                tabPositions = tabPositions,
                pagerState = pagerState
            )
        }
    ) {
        tabs.forEachIndexed { index, title ->
            val selected = index == pagerState.currentPage
            Tab(
                selected = selected,
                onClick = { scope.launch { pagerState.animateScrollToPage(index) } },
                modifier = Modifier.fillMaxHeight()
            ) {
                Text(
                    text = title,
                    fontSize = 14.sp,
                    color = if (selected) ColorPrimary else ColorTextNormal,
                    fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal
                )
            }
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun CommonIndexScrollableTabRow(
    tabs: List<String>,
    page: Int,
    modifier: Modifier = Modifier
        .fillMaxWidth()
        .height(42.dp),
    onTabClick: (Int) -> Unit
) {
    val scope = rememberCoroutineScope()
    ScrollableTabRow(
        selectedTabIndex = page,
        containerColor = Color.White,
        modifier = modifier,
        divider = {},
        edgePadding = 0.dp,
        indicator = { tabPositions ->
            CommonPageTabIndicator(
                tabPositions = tabPositions,
                page = page
            )
        }
    ) {
        tabs.forEachIndexed { index, title ->
            val selected = index == page
            Tab(
                selected = selected,
                onClick = { scope.launch { onTabClick(index) } },
                selectedContentColor = ColorPrimary,
                unselectedContentColor = Color.LightGray,
                modifier = Modifier
                    .fillMaxHeight()
                    .width(60.dp)
            ) {
                Text(
                    text = title,
                    fontSize = 14.sp,
                    color = if (selected) ColorPrimary else ColorTextNormal,
                    fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal
                )
            }
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun CommonTabIndicator(
    tabPositions: List<TabPosition>,
    pagerState: PagerState,
    color: Color = ColorPrimary,
    width: Dp = 20.dp,
    height: Dp = 2.dp,
) {
    val currentPage by rememberUpdatedState(newValue = pagerState.currentPage)
    val fraction by rememberUpdatedState(newValue = pagerState.currentPageOffsetFraction)
    val currentTab = tabPositions[currentPage]
    val previousTab = tabPositions.getOrNull(currentPage - 1)
    val nextTab = tabPositions.getOrNull(currentPage + 1)
    Canvas(
        modifier = Modifier
            .fillMaxSize()
            .padding(bottom = 5.dp),
        onDraw = {

            val indicatorWidth = width.toPx()
            val indicatorOffset = if (fraction > 0 && nextTab != null) {
                lerp(currentTab.left, nextTab.left, fraction).toPx()
            } else if (fraction < 0 && previousTab != null) {
                lerp(currentTab.left, previousTab.left, -fraction).toPx()
            } else {
                currentTab.left.toPx()
            }

            val canvasHeight = size.height
            drawRoundRect(
                color = color,
                topLeft = Offset(
                    indicatorOffset + ((currentTab.width.toPx() - indicatorWidth) / 2),
                    canvasHeight - height.toPx()
                ),
                size = Size(indicatorWidth + indicatorWidth * abs(fraction), height.toPx()),
                cornerRadius = CornerRadius(50f)
            )
        }
    )
}

@Composable
fun CommonPageTabIndicator(
    tabPositions: List<TabPosition>,
    page: Int,
    color: Color = ColorPrimary,
    width: Dp = 20.dp,
    height: Dp = 3.dp,
) {
    if (tabPositions.isEmpty()) {
        return
    }
    val currentTab = tabPositions[page]
    Canvas(
        modifier = Modifier
            .fillMaxSize()
            .padding(bottom = 5.dp),
        onDraw = {
            val indicatorWidth = width.toPx()
            val indicatorOffset = currentTab.left.toPx()
            val canvasHeight = size.height

            drawRoundRect(
                color = color,
                topLeft = Offset(
                    indicatorOffset + ((currentTab.width.toPx() - indicatorWidth) / 2),
                    canvasHeight - height.toPx()
                ),
                size = Size(indicatorWidth, height.toPx()),
                cornerRadius = CornerRadius(50f)
            )
        }
    )
}